<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表名" prop="tableName">
        <el-select v-model="queryParams.tableName" filterable placeholder="请选择表名">
          <el-option
            v-for="item in dict.type.sys_db_name"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleFieldAdd"
          v-hasPermi="['basic:translation:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:translation:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:translation:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="exportCSV"
          v-hasPermi="['system:translation:export']"
        >导出CSV
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:translation:export']"
        >导出excel
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportPdf"
          v-hasPermi="['system:translation:export']"
        >导出pdf
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="translationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id"/>
      <el-table-column label="表名" align="center" prop="tableName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_db_name" :value="scope.row.tableName"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="字段名" align="center" prop="fieldName"/>
      <el-table-column label="中文名" align="center" prop="fieldCnName"/>
      <el-table-column label="历史中文名" align="center" prop="oldCnName"/>
      <el-table-column label="翻译" align="center" prop="isTranslated">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isTranslated"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:translation:edit']"
          >修改
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['basic:translation:remove']"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改字段翻译映射对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表名" prop="tableName">
          <dict-tag :options="dict.type.sys_db_name" :value="form.tableName"></dict-tag>
        </el-form-item>
        <el-form-item label="字段名" prop="fieldName">
          <el-input v-model="form.fieldName" readonly/>
        </el-form-item>
        <el-form-item label="中文名" prop="fieldCnName">
          <el-input v-model="form.fieldCnName" placeholder="请输入中文名"/>
        </el-form-item>
        <!--        <el-form-item label="历史中文名" prop="oldCnName">-->
        <!--          <el-input v-model="form.oldCnName" placeholder="请输入历史中文名"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="翻译" prop="isTranslated">-->
        <!--          <el-switch-->
        <!--            v-model="form.isTranslated"-->
        <!--            active-color="#13ce66"-->
        <!--            inactive-color="#ff4949"-->
        <!--            :active-value="1"-->
        <!--            :inactive-value="0">-->
        <!--          </el-switch>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--  查询数据库的表  -->
    <field-table ref="fieldShow" @ok="handleQuery"/>
  </div>
</template>

<script>
import {
  listTranslation,
  getTranslation,
  delTranslation,
  addTranslation,
  updateTranslation
} from "@/api/basic/translation";
import fieldTable from "@/views/basic/translation/fieldTable.vue";

export default {
  name: "Translation",
  dicts: ['sys_db_name'],
  components: {fieldTable},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字段翻译映射表格数据
      translationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //导出CSV
    exportCSV() {
      // 准备CSV内容
      const headers = ['主键','表名','字段名', '中文名','历史中文名','翻译'];
      const rows = this.translationList.map((user,index) => [user.id,user.tableName,user.fieldName,user.fieldCnName,user.oldCnName,user.isTranslated]);

      // 添加表头
      const csvContent = [headers, ...rows]
        .map(row => row.join(','))
        .join('\n');

      // 创建下载链接
      const blob = new Blob([`\uFEFF${csvContent}`], {
        type: 'text/csv;charset=utf-8;'
      });
      const link = document.createElement('a');

      link.href = URL.createObjectURL(blob);
      link.download = '字段映射翻译.csv';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    /** 查询字段翻译映射列表 */
    getList() {
      this.loading = true;
      listTranslation(this.queryParams).then(response => {
        this.translationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tableName: null,
        fieldName: null,
        fieldCnName: null,
        oldCnName: null,
        isTranslated: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加字段翻译映射";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTranslation(id).then(response => {
        this.form = response.data;
        this.form.oldCnName = row.fieldCnName;
        this.open = true;
        this.title = "修改字段翻译映射";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.oldCnName.trim() === this.form.fieldCnName.trim()){
              this.$modal.msgError("中文名不能与历史中文名相同");
              return;
            }
            updateTranslation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTranslation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除字段翻译映射编号为"' + ids + '"的数据项？').then(function () {
        return delTranslation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/field/translation/export', {
        ...this.queryParams
      }, `translation_${new Date().getTime()}.xlsx`)
    },
    // 导出pdf
    handleExportPdf(){
      this.download('basic/field/translation/exportPdf',{},`translation_${new Date().getTime()}.pdf`)
    },
    // 打开新增字段翻译弹框
    handleFieldAdd() {
      this.$refs.fieldShow.show();
    },
    // 修改翻译状态
    handleChange(row) {
      if (row.isTranslated === 1) {
        if (row.fieldCnName.trim().length > 0) {
          this.$modal.confirm('是否确认修改翻译状态为开启？').then(() => {
            return updateTranslation(row);
          }).then(() => {
            this.getList();
          }).catch(() => {
            // 可以在这里添加一些错误处理逻辑
            this.$modal.msgError("开启翻译失败");
          });
        } else {
          row.isTranslated = 0;
          this.$modal.msgError("请先维护字段中文名后再启用翻译！");
        }
      } else if (row.isTranslated === 0) {
        updateTranslation(row).then(() => {
          this.getList();
        }).catch(() => {
          // 可以在这里添加一些错误处理逻辑
          this.$modal.msgError("修改失败");
        });
      }
    }
  }
};
</script>
